package com.xzjt.web.controller.system;

import java.util.Iterator;
import java.util.List;

import com.xzjt.common.constant.UserConstants;
import com.xzjt.common.core.domain.entity.SysOrg;
import com.xzjt.common.utils.SecurityUtils;
import com.xzjt.common.utils.StringUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.xzjt.common.annotation.Log;
import com.xzjt.common.core.controller.BaseController;
import com.xzjt.common.core.domain.R;
import com.xzjt.common.enums.BusinessType;
import com.xzjt.system.service.ISysOrgService;


/**
 * 组织机构Controller
 *
 * @author xzjt
 * @date 2021-09-01
 */
@RestController
@RequestMapping("/system/org")
public class SysOrgController extends BaseController {
    @Autowired
    private ISysOrgService sysOrgService;

    /**
     * 获取组织机构列表
     */
    @PreAuthorize("@ss.hasPermi('system:org:list')")
    @GetMapping("/list")
    public R list(SysOrg org)
    {
        List<SysOrg> orgs = sysOrgService.selectSysOrgList(org);
        return R.success(orgs);
    }

    /**
     * 查询组织机构列表（排除节点）
     */
    @PreAuthorize("@ss.hasPermi('system:org:list')")
    @GetMapping("/list/exclude/{orgId}")
    public R excludeChild(@PathVariable(value = "orgId", required = false) Long orgId)
    {
        List<SysOrg> orgs = sysOrgService.selectSysOrgList(new SysOrg());
        Iterator<SysOrg> it = orgs.iterator();
        while (it.hasNext())
        {
            SysOrg d = (SysOrg) it.next();
            if (d.getOrgId().intValue() == orgId
                    || ArrayUtils.contains(StringUtils.split(d.getAncestors(), ","), orgId + ""))
            {
                it.remove();
            }
        }
        return R.success(orgs);
    }

    /**
     * 根据组织机构编号获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:org:query')")
    @GetMapping(value = "/{orgId}")
    public R getInfo(@PathVariable Long orgId)
    {
        return R.success(sysOrgService.selectOrgById(orgId));
    }

    /**
     * 获取组织机构下拉树列表
     */
    @GetMapping("/treeselect")
    public R treeselect(SysOrg org)
    {
        List<SysOrg> orgs = sysOrgService.selectSysOrgList(org);
        return R.success(sysOrgService.buildOrgTreeSelect(orgs));
    }



    /**
     * 新增组织机构
     */
    @PreAuthorize("@ss.hasPermi('system:org:add')")
    @Log(title = "组织机构管理", businessType = BusinessType.INSERT)
    @PostMapping
    public R add(@Validated @RequestBody SysOrg org){
        if (UserConstants.NOT_UNIQUE.equals(sysOrgService.checkOrgNameUnique(org))){
            return R.error("新增组织机构'" + org.getOrgName() + "'失败，组织机构名称已存在");
        }
        org.setCreateBy(SecurityUtils.getUsername());
        return toAjax(sysOrgService.insertOrg(org));
    }

    /**
     * 修改组织机构
     */
    @PreAuthorize("@ss.hasPermi('system:org:edit')")
    @Log(title = "组织机构管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public R edit(@Validated @RequestBody SysOrg org)
    {
        if (UserConstants.NOT_UNIQUE.equals(sysOrgService.checkOrgNameUnique(org)))
        {
            return R.error("修改组织机构'" + org.getOrgName() + "'失败，组织机构名称已存在");
        }
        else if (org.getParentId().equals(org.getOrgId()))
        {
            return R.error("修改组织机构'" + org.getOrgName() + "'失败，上级组织机构不能是自己");
        }
        else if (StringUtils.equals(UserConstants.DEPT_DISABLE, org.getStatus())
                && sysOrgService.selectNormalChildrenOrgById(org.getOrgId()) > 0)
        {
            return R.error("该组织机构包含未停用的子组织机构！");
        }
        org.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(sysOrgService.updateOrg(org));
    }

    /**
     * 删除组织机构
     */
    @PreAuthorize("@ss.hasPermi('system:org:remove')")
    @Log(title = "组织机构管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{orgId}")
    public R remove(@PathVariable Long orgId)
    {
        if (sysOrgService.hasChildByOrgId(orgId))
        {
            return R.error("存在下级组织机构,不允许删除");
        }
        if (sysOrgService.checkOrgExistUser(orgId))
        {
            return R.error("组织机构存在用户,不允许删除");
        }
        return toAjax(sysOrgService.deleteOrgById(orgId));
    }
}
